package alp.starcode.nudtportal.framework.config.rabbitmq;

import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.HttpStatus;
import org.apache.http.StatusLine;
import org.apache.http.auth.AuthScope;
import org.apache.http.auth.UsernamePasswordCredentials;
import org.apache.http.client.CredentialsProvider;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPut;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.BasicCredentialsProvider;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.util.EntityUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Profile;
import org.springframework.stereotype.Component;

/**
 * 调用rabbitmq提供的API示例
 *
 * @Author wj
 * @Date 2023/8/1
 * @Version 1.0
 */

@Slf4j
@Component
public class RabbitMqApi {
    @Value("${spring.rabbitmq.addresses}")
    private String addresses;

    @Value("${spring.rabbitmq.username}")
    private String username;

    @Value("${spring.rabbitmq.password}")
    private String password;

    /**
     * 新增vhost
     *
     * @param vhostName
     */
    public void addVhost(String vhostName) {
        String url = "http://" + getAddress() + ":15672/api/vhosts/" + vhostName;
        HttpPut httpPut = new HttpPut(url);

        try (CloseableHttpClient pClient = getBasicHttpClient();
             CloseableHttpResponse response = pClient.execute(httpPut)) {
//            response = pClient.execute(httpPut)
            StatusLine status = response.getStatusLine();
            int state = status.getStatusCode();
            if (state == HttpStatus.SC_CREATED) {
                EntityUtils.toString(response.getEntity());
                log.info("添加vhost：" + vhostName + "成功");
            } else if (state == HttpStatus.SC_NO_CONTENT) {
                log.info("vhost已存在");
            } else {
                log.info("请求返回：" + state + "(" + url + ")");
            }
        } catch (Exception e) {
            log.error("地址url:" + url + ",异常" + e.toString());
        }
    }

    /**
     * 给指定用户授予指定vhost的指定权限
     *
     * @param vhostName
     * @param configure
     * @param read
     * @param write
     */
    public void addVhostPermissions(String vhostName, String configure, String read, String write) {
        String url = "http://" + getAddress() + ":15672/api/permissions/" + username;
        HttpPut httpPut = new HttpPut(url);
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("configure", configure);
        jsonObject.put("read", read);
        jsonObject.put("write", write);
        StringEntity stringEntity = new StringEntity((JSONObject.toJSONString(jsonObject)), "UTF-8");
        httpPut.setEntity(stringEntity);
        try (
                CloseableHttpClient pClient = getBasicHttpClient();
                CloseableHttpResponse response = pClient.execute(httpPut)
        ) {
            StatusLine status = response.getStatusLine();
            int state = status.getStatusCode();
            if (state == HttpStatus.SC_CREATED) {
                String str = EntityUtils.toString(response.getEntity());
                log.info("授权成功");
            } else if (state == HttpStatus.SC_NO_CONTENT) {
                log.info("已存在授权");
            } else {
                log.info("请求返回：" + state + "(" + url + ")");
            }
        } catch (Exception e) {
            log.error("地址url:" + url + "，异常：" + e.toString());
        }
    }

    /**
     * 创建CloseableHttpClient
     */
    private CloseableHttpClient getBasicHttpClient() {
        HttpClientBuilder httpClientBuilder = HttpClientBuilder.create();

        //设置BasicAuth
        CredentialsProvider provider = new BasicCredentialsProvider();
        AuthScope scope = new AuthScope(AuthScope.ANY_HOST, AuthScope.ANY_PORT, AuthScope.ANY_REALM);
        UsernamePasswordCredentials credentials = new UsernamePasswordCredentials(username, password);
        provider.setCredentials(scope, credentials);
        httpClientBuilder.setDefaultCredentialsProvider(provider);
        return httpClientBuilder.build();

    }

    /**
     * 解决集群环境下地址多个问题
     */
    private String getAddress() {
        return addresses.split(":")[0];
    }
}
